/* Copyright (c) 2014.*/
package au.com.cba;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import au.com.cba.workitem.service.WorkItemCompletionCallbackService;
import au.com.cba.workitem.service.WorkItemService;
import au.com.cba.workitem.serviceImpl.WorkItemCompletionCallbackServiceImpl;


/**
 * The Class WorkItemThreadPool.
 * @author Magesh Ravichandran
 */
public class WorkItemThreadPool {
	
	/** The worker queue. */
	private final BlockingQueue<WorkItemService> workerQueue;
    
    /** The worker threads. */
    private final Thread[] workerThreads;
 
    /**
     * Instantiates a new work item thread pool.
     *
     * @param numThreads the num threads
     */
    public WorkItemThreadPool(int numThreads) {
        workerQueue = new LinkedBlockingQueue<WorkItemService>();
        workerThreads = new Thread[numThreads];
 
        int i = 0;
        for (Thread t : workerThreads) {
            i++;
            t = new WorkItemThread("Pool Thread "+i);
            t.start();
        }
    }
    
    /**
     * Adds the task.
     *
     * @param w the w
     */
    public void addTask(WorkItemService w){
        try {
            workerQueue.put(w);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * The Class WorkItemThread.
     */
    class WorkItemThread extends Thread {

        
        /**
         * Instantiates a new work item thread.
         *
         * @param name the name
         */
        public WorkItemThread(String name){
            super(name);
        }
        
        /* (non-Javadoc)
         * @see java.lang.Thread#run()
         */
        public void run() {
            while (true) {
                try {
            		WorkItemCompletionCallbackService workItemCompletionCallbackService = new WorkItemCompletionCallbackServiceImpl(); 
                    WorkItemService r = workerQueue.take();
                    r.execute(workItemCompletionCallbackService);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }
            }
        }
    
    }
}
